package com.windowes.weichang.service;

import com.google.gson.Gson;
import com.windowes.weichang.common.AMapConfig;
import com.windowes.weichang.common.AmapResponse;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.model.BDShop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/6/27 下午9:10
 * @description:高德地图
 *
 **/
@Service
@Slf4j
public class AMapService {

    public static final String POI_CREATE = "http://yuntuapi.amap.com/datamanage/data/create";
    public static final String POI_UPDATE = "http://yuntuapi.amap.com/datamanage/data/update";
    public static final String GEO_SEARCH = "http://yuntuapi.amap.com/datasearch/around";
    public static final String LOCAL_SEARCH = "http://yuntuapi.amap.com/datasearch/local";

    public static final String geotable_id = "5b337a152376c12776c545e7";


    @Autowired
    AMapConfig aMapConfig;
    @Autowired
    RestTemplate restTemplate;


    /**
     * 数据同步
     *
     * @param title
     * @param address
     * @param longitude
     * @param latitude
     * @param shopkeeper
     * @param shopId
     * @return
     */
    public ServerResponse dsJob(String title, String address, BigDecimal longitude, BigDecimal latitude, String shopkeeper, Integer shopId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("loctype", "1");
        map.add("tableid", geotable_id);
        map.add("key", aMapConfig.getKey());

        Map dataParam = new HashMap();
        dataParam.put("_name", title);
        dataParam.put("_location", longitude + "," + latitude);
        dataParam.put("_address", address);
        dataParam.put("shopId", shopId);
        dataParam.put("shopkeeper", shopkeeper);


        map.add("data", new Gson().toJson(dataParam));
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(POI_CREATE, request, String.class);
        log.info("同步结果为:{}", stringResponseEntity.getBody());
        if (stringResponseEntity.getStatusCode() == HttpStatus.OK) {
            HashMap hashMap = new Gson().fromJson(stringResponseEntity.getBody(), HashMap.class);
            String geoId = (String) hashMap.get("_id");
            return ServerResponse.createBySuccess("创建成功!", geoId);
        }
        return ServerResponse.createByErrorMessage("创建失败!");
    }


    /**
     * 更新单条数据信息
     * @param title
     * @param address
     * @param longitude
     * @param latitude
     * @param shopkeeper
     * @param shopId
     * @return
     */
    public ServerResponse updateItem(String geoId,String title, String address, BigDecimal longitude, BigDecimal latitude, String shopkeeper, Integer shopId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("loctype", "1");
        map.add("tableid", geotable_id);
        map.add("key", aMapConfig.getKey());

        Map dataParam = new HashMap();
        dataParam.put("_id", geoId);
        dataParam.put("_name", title);
        dataParam.put("_location", longitude + "," + latitude);
        dataParam.put("_address", address);
        dataParam.put("shopId", shopId);
        dataParam.put("shopkeeper", shopkeeper);


        map.add("data", new Gson().toJson(dataParam));
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(POI_UPDATE, request, String.class);
        log.info("更新结果为:{}", stringResponseEntity.getBody());
        if (stringResponseEntity.getStatusCode() == HttpStatus.OK) {
            return ServerResponse.createBySuccessMessage("创建成功!");
        }
        return ServerResponse.createByErrorMessage("创建失败!");
    }

    /**
     * POI搜索【百度】
     *
     * @param location 116.395884,39.932154
     * @param radius   1000
     * @param tags     酒店
     * @return
     */
    public ServerResponse<List<BDShop>> search(String location, String radius, String tags, String q) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(GEO_SEARCH)
                .queryParam("key", aMapConfig.getKey())
                .queryParam("tableid", geotable_id)
                .queryParam("center", location)
                .queryParam("radius", radius)
                .queryParam("keywords", q)
                .queryParam("sortrule", "_distance")
                .queryParam("page", 1)
                .queryParam("limit", 100);

        HttpEntity<?> entity = new HttpEntity<>(headers);
        HttpEntity<String> response = restTemplate.exchange(
                builder.build().encode().toUri(),
                HttpMethod.GET,
                entity,
                String.class);

        AmapResponse bdResponse = new Gson().fromJson(response.getBody(), AmapResponse.class);
        if (bdResponse != null && bdResponse.getDatas() != null && !bdResponse.getDatas().isEmpty()) {
            return ServerResponse.createBySuccess(bdResponse.getDatas());
        }
        return ServerResponse.createByErrorMessage("未查询到相关店铺");
    }


    /**
     * 附近搜索
     *
     * @param region 北京
     * @param tags   酒店
     * @return
     */
    public ServerResponse<List<BDShop>> geosearch(String region, String tags) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(LOCAL_SEARCH)
                .queryParam("key", aMapConfig.getKey())
                .queryParam("tableid", geotable_id)
                .queryParam("city", region)
                .queryParam("keywords", " ")
                .queryParam("page", 0)
                .queryParam("limit", 100);

        HttpEntity<?> entity = new HttpEntity<>(headers);
        HttpEntity<String> response = restTemplate.exchange(
                builder.build().encode().toUri(),
                HttpMethod.GET,
                entity,
                String.class);

        Gson gson = new Gson();
        AmapResponse bdResponse = gson.fromJson(response.getBody(), AmapResponse.class);
        if (bdResponse != null && bdResponse.getDatas() != null && !bdResponse.getDatas().isEmpty()) {
            return ServerResponse.createBySuccess(bdResponse.getDatas());
        }
        return ServerResponse.createByErrorMessage("未查询到相关店铺");
    }


}
